<?php

/**
 * This file is part of the Codizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Codizer Core Team <team@codizer.org>
 * @package     Codizer
 */

class f_exception_BaseException extends Exception
{
    public static function exceptionHandler($exception)
    {
        $err = false;
        if(func_num_args() == 2)
        {
            $err = func_get_arg(1);
        }

        $label = 'CAUGHT EXCEPTION';

        if(!is_null($err) && $err != false)
        {
          $errorType = array (
                       E_ERROR            => 'ERROR',
                       E_WARNING        => 'WARNING',
                       E_PARSE          => 'PARSING ERROR',
                       E_NOTICE         => 'NOTICE',
                       E_CORE_ERROR     => 'CORE ERROR',
                       E_CORE_WARNING   => 'CORE WARNING',
                       E_COMPILE_ERROR  => 'COMPILE ERROR',
                       E_COMPILE_WARNING => 'COMPILE WARNING',
                       E_USER_ERROR     => 'USER ERROR',
                       E_USER_WARNING   => 'USER WARNING',
                       E_USER_NOTICE    => 'USER NOTICE',
                       E_STRICT         => 'STRICT NOTICE',
                       E_RECOVERABLE_ERROR  => 'RECOVERABLE ERROR'
                       );

            // get error message
            if (array_key_exists($err, $errorType))
            {
                $label = $errorType[$err];
            }
        }

        $logger = f_logs_Logger::getInstance();
        $message = $exception->getMessage();
        $traceData = $exception->getTrace();
        $file = $exception->getFile();
        $line = $exception->getLine();

        $traceData[0]['class'] = $traceData[1]['class'];
        $traceData[0]['type'] = $traceData[1]['type'];
        $traceData[0]['function'] = $traceData[1]['function'];

        if(CLI_MODE)
        {
            echo COLOR_BEIGE."(!)".COLOR_RED." $label".COLOR_NORMAL." : ".$message.' in '.$file.' line '.$line."\n\n";

			$i = count($traceData);

			echo "Call Stack:\n";
            foreach ($traceData as $line)
            {
                 echo $i." \t ".$line['class'].$line['type'].$line['function']."() \t ".str_replace(BASE_DIR.DS, '', $line['file']).':'.$line['line']."\n";
				 $i--;
            }

            die();
        }   

		$logger->errorLog($file." (ln.".$line.") - ".$message);

    	$class  = (isset($traceData[0]["class"])) ? $traceData[0]["class"] : 'N/A';

				echo '<!DOCTYPE html
				      PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
				      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
				      <html xmlns="http://www.w3.org/1999/xhtml"
						    xml:lang="en" lang="en">
				      <head>
				      <meta http-equiv="Content-Type"
						    content="text/html; charset=utf-8"/>
				      <title>ERROR</title>
				      <style type="text/css">

				      #exception {
						  background-color: #EEEEEE;
						  border:           solid 1px #000;
						  font-family:      verdana, helvetica, sans-serif;
						  font-size:        76%;
						  font-style:       normal;
						  font-weight:      normal;
						  margin:           10px;
				      }

				      #help {
						  color:     #750000;
						  font-size: 0.9em;
				      }

				      .message {
						  color:       #FF0000;
						  font-weight: bold;
				      }

				      .title {
						  font-size:   1.1em;
						  font-weight: bold;
				      }

				      td {
						  background-color: #EEEEEE;
						  padding:          5px;
				      }

				      th {
						  background-color: #750000;
						  color:            #FFFFFF;
						  font-size:        1.2em;
						  font-weight:      bold;
						  padding:          5px;
						  text-align:       left;
                          border: 1px solid #000;
				      }

                      tr.list td { border: 1px solid black; }

                      .textright { text-align:right; }
                      .textmid { text-align: center; }


                      .error { color: #FCE94F; background-color: #CC0000; font-size: 1.5em; padding: 2px; }
                      
				      </style>
				      </head>
				      <body>
                      <div id="exceptionContainer">
				      <table id="exception" cellpadding="0" cellspacing="0">
						  <tr>
						      <th colspan="4"><span class="error">( ! )</span> '.$label.'</th>
						  </tr>
						  <tr>
						      <td class="title">Message :</td>
						      <td class="message" colspan="3">' . $message . '</td>
						  </tr>
						  <tr>
						      <td class="title">Class :</td>
						      <td colspan="3">' .$class. '</td>
						  </tr>
						  <tr>
						      <td class="title">Location :</td>
						      <td colspan="3">' . str_replace(BASE_DIR.DS, '', $file) . '</td>
						  </tr>
						  <tr>
						      <td class="title">Line :</td>
						      <td colspan="3">' . $line . '</td>
						  </tr>';

				if (count($traceData) > 0)
				{

				    echo '<tr>
						      <th colspan="4">Call Stack</th>
						  </tr>
                          <tr>
                              <th>#</th><th>Function</th><th>Line</th><th>Location</th>
                          </tr>';

				   	$i = count($traceData);

				    foreach ($traceData as $line)
				    {
				    	$args = "";
                        
				    	if(isset($line['args']) && is_array($line['args']))
				    	{
				    		foreach ($line['args'] as $arg)
				    		{
				    			if(is_string($arg)) $arg = "\"$arg\"";

				    			if(is_null($arg)) $arg = "null";

				    			if(!is_object($arg))
				    			{
				    				$args .= $arg.", ";
				    			}
				    		}
				    		$args = substr($args, 0, -2);
				    	}

				    	if(isset($line['line']) && isset($line['class']) && isset($line['type']) && isset($line['function']) && isset($line['file']))
				    	{
						echo '<tr class="list">
							  <td class="textmid">'.$i.'</td><td>'.$line['class'].$line['type'].$line['function'].'('.$args.')</td><td class="textmid">'.$line['line'].'</td><td>'.str_replace(BASE_DIR.DS, '', $line['file']).'</td>
						      </tr>';
				    	}

						$i--;

				    }

				}

				echo     '
				      </table>
                      </div>
				      </body>
				      </html>';

        $firePHP = f_logs_Logger::getInstance()->getFirePHPLogger();

		if(is_object($firePHP))
		{
			$firePHP->error($traceData, "EXCEPTION : ".$message." (".$file." @ line ".$line.")");
		}

        die;
    }
}